﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsMine.DomainObjects;
using System.Web;

namespace NewsDiscoveryEngine
{
    [Serializable]
    public class HtmlString2LinksJob:BaseJob
    {
        public HtmlContentFromUrl HtmlContent { get; set; }

        public override bool ExecuteJob()
        {
            var result = GetLinksFromHtmlContent(HtmlContent);
            ProcessOutput(result);
            return true;
        }

        public static List<HtmlLink> GetLinksFromHtmlContent(HtmlContentFromUrl htmlContent)
        {
           var htmlLinks =  NewsMine.Utilities.WebHelper.GetHtmlLinks(htmlContent.Url, htmlContent);
           HtmlLink hLink;

           bool isFinalUrlIsRedirected = false;

           if (htmlContent.Url != htmlContent.FinalUrl)
           {
               isFinalUrlIsRedirected = true;
           }

           for (int i = 0; i < htmlLinks.Count; i++)
           {
               hLink = htmlLinks[i];

               if (!string.IsNullOrEmpty(hLink.Title))
               {
                   hLink.Title = hLink.Title.Trim();
                   hLink.Title = HttpUtility.HtmlDecode(hLink.Title);
               }
               if (!string.IsNullOrEmpty(hLink.Link))
               {
                   hLink.Link = hLink.Link.Trim();
               }

               if (hLink.IsFeedSourced == true)
               {
                   if (!string.IsNullOrEmpty(hLink.Description))
                   {
                       hLink.Description = HttpUtility.HtmlDecode(hLink.Description);
                   }
               }

               if (isFinalUrlIsRedirected == true && !string.IsNullOrEmpty(htmlContent.FinalUrl))
               {
                   hLink.OriginalRefUrl = htmlContent.FinalUrl;
               }

               hLink.PubDate = htmlContent.DownloadedTimeStamp;
           }

           return htmlLinks;
        }
    }
}
